package com.mzy.NetworkProgram.UdpSocket;

import com.mzy.basics.network.Utils;

import java.io.IOException;
import java.net.*;
import java.util.Arrays;
import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author mzy
 * @Date 2022/5/16 17:15
 * @Version 1.0
 */
// 接收端
public class MulticastReceive
{
    public static void main(String[] args) throws IOException
    {
        MulticastSocket ds = null;
        DatagramPacket packet = null;
        try {
            //使用多播
            ds = new MulticastSocket(1616);
            InetAddress  receiveAddress=InetAddress.getByName("224.0.0.5");
            //获取有效网卡地址
            Set<NetworkInterface> physicalNICs = Utils.getPhysicalNICs();
            //端口不冲突就行
            for (NetworkInterface networkInterface : physicalNICs) {
//                if (networkInterface.getName().indexOf("eth2")>=0){
//                    continue;
//                }
                System.out.println("监听："+networkInterface.getName());

                InetSocketAddress inetSocketAddress = new
                        InetSocketAddress("224.0.0.5", 0);
                System.out.println(inetSocketAddress.getAddress());
                //将有效网卡加入组播
                ds.joinGroup(inetSocketAddress, networkInterface);
            }
            DatagramPacket recvPack = new DatagramPacket(new byte[1024], 1024);
            while (true) {
                ds.receive(recvPack);
                byte[] bytes = Arrays.copyOfRange(recvPack.getData(), 0, recvPack.getLength());
                System.out.println(recvPack.getSocketAddress()+"Server receive msg:" + new String(bytes));
                System.out.println("启动监听完成");
            }
        } catch (Exception e) {
            System.out.println("寻址监听出错" + e);
            e.printStackTrace();
        } finally {
            if(ds!=null){
                ds.close();
            }
        }
    }
}